package com.ruoyi.quartz.task;

import com.ruoyi.bizsys.domain.CustBankCard;
import com.ruoyi.bizsys.domain.CustBindCardLog;
import com.ruoyi.bizsys.service.ICustBindCardLogService;
import com.ruoyi.business.mapper.BusinessMapper;
import com.ruoyi.business.service.IBankCardService;
import com.ruoyi.bizsys.utils.BizConstants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysDictDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

/**
 * @Author: Jamnsin
 * @Date: 2021/3/30 10:39 上午
 */
@Slf4j
@Component("bindCardTask")
public class BindCardTask {

    @Autowired
    ICustBindCardLogService custBindCardLogService;

    @Autowired
    IBankCardService bankCardService;

    @Autowired
    BusinessMapper businessMapper;

    @Autowired
    ISysDictDataService sysDictDataService;

    public void queryBindRst() {
        log.info("查询绑定结果任务 Start >>>>>>>>>>");

        List<CustBindCardLog> custBindCardLogs = businessMapper.selectBindCardPending();
        log.info("待处理的状态为等待用户提交认证的数据为：{} 条", custBindCardLogs.size());

        if (CollectionUtils.isEmpty(custBindCardLogs)) {
            log.info("查询绑定结果任务 End >>>>>>>>>>");
            return;
        }

        custBindCardLogs.stream().forEach(p -> {
            try {
                double interval = DateUtils.getDateDiff(7, new Date(), p.getCreateTime());
                if (interval < 120) {
                    log.debug("{} 创建时间不足120秒", p.getBindSerialNo());
                    return;
                }

                interval = DateUtils.getDateDiff(1, new Date(), p.getCreateTime());
                if (interval >= 2 && !rerunSwitch()) {
                    CustBindCardLog cardLog = new CustBindCardLog();
                    cardLog.setId(p.getId());
                    cardLog.setTransStatus(BizConstants.BIND_CARD_TRANS_TIMEOUT);
                    custBindCardLogService.updateCustBindCardLog(cardLog);
                    return;
                }

                if (StringUtils.equals(p.getTransStatus(), BizConstants.BIND_CARD_TRANS_SUCCESS)) {
                    return;
                }
                bankCardService.verifyTransaction(p);
            } catch (Exception e) {
                log.error("验证绑卡交易异常，bindSerialNo = " + p.getBindSerialNo(), e);
            }

        });

        log.info("查询绑定结果任务 End >>>>>>>>>>");
    }

    private boolean rerunSwitch() {
        return Integer.valueOf(getDictLable("biz_switch", "bind_card_failed_Rerun")) == 1;
    }

    protected String getDictLable(String dictType, String dictValue) {
        return sysDictDataService.selectDictLabel(dictType, dictValue);
    }
}
